package DAOS;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import Hibernate.HibernateUtil;
import Negocio.Medico;

public class MedicoDAO {

	private static MedicoDAO instancia = null;
	
	private static SessionFactory sf = null;

	public static MedicoDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new MedicoDAO();
		} 
		return instancia;
	}
	
	
	public void guardarMedico(Medico m){

		Session session = sf.openSession();
		session.beginTransaction();
		session.persist(m);
		session.flush();
		session.getTransaction().commit();
		session.close();

	}


	public void eliminarMedico(Medico m){

		Session session = sf.openSession();
		session.beginTransaction();
		session.delete(m);
		session.flush();
		session.getTransaction().commit();
		session.close();

	}


	public void modificarMedico(Medico m){

		Session session = sf.openSession();
		session.beginTransaction();
		session.update(m);
		session.flush();
		session.getTransaction().commit();
		session.close();

	}


	public List<Object[]> listarMedicos(){
		
		Session session = sf.openSession();
		Query q = session.createQuery
		(
				"SELECT m.nombre, m.apellido, m.matricula" +
				"FROM Medico m"
		);
		
		@SuppressWarnings("unchecked")
		List<Object[]> medicos = new ArrayList<Object[]>(q.list());
		session.close();
		return medicos;
	}


	
	@SuppressWarnings("unchecked")
	public List<Medico> cargarMedicos () {
		Session session = sf.openSession();
		Query q = session.createQuery(
					"SELECT m.idMedico, m.nombre, m.apellido, m.direccion, m.telefono, m.fechaNacimiento, m.matricula" +
					"FROM Medico m"
		);
		
		@SuppressWarnings("unchecked")
		List<Medico> mm = new ArrayList<Medico>(q.list());
		
		AgendaDAO ag = AgendaDAO.getInstancia();
		
		for (Medico medico : mm) {
			Query q1 = session.createQuery(
					"SELECT e.idEspecialidad, e.nombre" +
					"FROM Especialidad e JOIN Medico m" +
					"WHERE m.idMedico = " + medico.getIdMedico() +
					"and e.idEspecialidad = m.idEspecialidad"
				
		);
		
		medico.setEspecialidades(q1.list());
			
		medico.setAgenda(ag.cargarAgenda(medico));
		
		}
		
		session.close();
		
		return mm;
		
	}
	public Medico cargarUnMedico (long DNI) {
		Medico m = new Medico();
		Session session = sf.openSession();
		session.load(m, DNI);
		session.close();
	
		return m;
	}
}
